import dayjs from "dayjs";

// 阿里云链接下载文件
export function downloadOssFile(url, filename) {
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = url;
      // 获取当前时间戳
      const timestamp = new Date().getTime();
      // 拼接时间戳到文件名
      a.download = `${filename.replace(".xlsx", "")}_${timestamp}.xlsx`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    })
    .catch(err => console.log(err));
}
// 文件下载
export function downloadFile(filename: string, dataURL: string): void {
  const aLink = document.createElement("a");
  aLink.download = filename;
  aLink.href = dataURL;
  aLink.click();
}

// base64 转图片
export function base64ToImg(base64: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    if (!base64 || !base64.startsWith("data:image/")) {
      reject(new Error("Invalid base64 format"));
      return;
    }

    const img = new Image();
    img.src = base64;

    img.addEventListener("load", () => {
      resolve(img);
    });

    img.addEventListener("error", error => {
      reject(new Error("Failed to load image: " + error.message));
    });
  });
}

// 图片转canvas
export function imgToCanvas(img: HTMLImageElement): HTMLCanvasElement {
  if (!(img instanceof HTMLImageElement)) {
    throw new Error("Invalid image element");
  }

  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;

  const ctx = canvas.getContext("2d");
  if (!ctx) {
    throw new Error("Failed to get 2D rendering context");
  }

  if (img.width <= 0 || img.height <= 0) {
    throw new Error("Image dimensions must be greater than 0");
  }

  ctx.drawImage(img, 0, 0);

  return canvas;
}

// 添加水印  includeLastRow 是否包含最后一行
export function addWatermark(canvas: HTMLCanvasElement, watermarkText: string = "", includeLastRow: boolean = true) {
  const ctx = canvas.getContext("2d")!;
  const fontSize = 40;
  const fontColor = "rgba(128, 128, 128, 0.1)";
  const gridSpacing = 500;

  // 获取当前日期并格式化为 YYYY-MM-DD 格式
  const currentDate = dayjs().format("YYYY-MM-DD");
  const fullWatermarkText = `waiting ${watermarkText} ${currentDate}`;

  ctx.font = `${fontSize}px Arial`;
  ctx.fillStyle = fontColor;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";

  // 设置阴影效果
  // ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
  // ctx.shadowBlur = 5
  // ctx.shadowOffsetX = 2
  // ctx.shadowOffsetY = 2

  // 辅助函数：绘制单个水印
  const drawWatermark = (x: number, y: number) => {
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(-Math.PI / 6); // 旋转角度，可以根据需要调整
    ctx.fillText(fullWatermarkText, 0, 0);
    ctx.restore();
  };

  // 计算每行水印的数量
  const numWatermarksPerRow = Math.floor((canvas.width + gridSpacing) / gridSpacing);
  const numWatermarksPerCol = Math.floor((canvas.height + gridSpacing) / gridSpacing);

  // 计算每个水印的实际间隔
  const actualGridSpacingX = canvas.width / numWatermarksPerRow;
  const actualGridSpacingY = canvas.height / numWatermarksPerCol;

  // 绘制主网格
  for (let i = 0; i < numWatermarksPerRow; i++) {
    for (let j = 0; j < (includeLastRow ? numWatermarksPerCol : numWatermarksPerCol - 1); j++) {
      const posX = i * actualGridSpacingX + actualGridSpacingX / 2;
      const posY = j * actualGridSpacingY + actualGridSpacingY / 2;
      drawWatermark(posX, posY);
    }
  }
}

export function ranDomFileName(fileName: string): string {
  return dayjs().format("YYYYMMDDHHmmss") + fileName;
}

/**
 * 判断path是否为外链
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}
